package Coffee.service;

import Coffee.bean.Coffee;
import Coffee.bean.Order;
import Coffee.bean.User;
import Coffee.dao.OrderDao;
import Coffee.dao.OrderDaoImpl;
import Coffee.util.Cbase;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public class OrderServiceImpl extends Cbase implements OrderService {
    UserService userService = new UserServiceImpl();
    CoffeeService coffeeService = new CoffeeServiceImpl();
    OrderDao orderDao = new OrderDaoImpl();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formattedDate = LocalDateTime.now().format(formatter);

    @Override
    public void insertOrder(String username, String cofname, int cofcount) {
        //传入的是用户名，coffee名，数量，先查询用户名判断是否存在，然后咖啡名是否存在，返回id和价格
        User user = userService.queryUser(username);
        if (user == null) {
            return;
        }
        Coffee coffee = coffeeService.selectbyname(cofname);
        if (coffee == null) {
            return;
        }
        if (!Objects.equals(coffee.getState(), "在售")) {
            System.out.println("该饮品已经售完");
            return;
        }
        int coftotal = cofcount * coffee.getCofprice();
        try {
            int i = orderDao.insertOrder(UUID.randomUUID().toString().replaceAll("-", ""), user.getUserid(),
                    username, coffee.getCofid(), cofname, cofcount, coftotal, formattedDate);
            if (i == 1) {
                System.out.println("下单成功");
            } else {
                System.out.println("下单失败");
            }
        } catch (Exception e) {
            System.out.println("下单过程中发生错误: " + e.getMessage());
        }
    }

    @Override
    public List<Order> queryOrder(String username) {
        return orderDao.queryOrder(username);

    }

    @Override
    public List<Order> queryOrderAll() {
        return orderDao.queryOrderAll();
    }

    @Override
    public List<Order> queryOrderByState(String username, String orderstate) {
        return orderDao.queryOrderByState(username,orderstate);
    }

    @Override
    public void updateOrderState(String orderstate, String orderid) {
        int i = orderDao.updateOrderState(orderstate, orderid);
        boolean od = (i!=0);
        System.out.println(od?"修改成功":"修改失败");
    }

    @Override
    public Order queryOrderByOrderId(String orderid) {
        return orderDao.queryOrderByOrderId(orderid);
    }

    @Override
    public List<Order> queryOrderAdmin(String username) {
        return orderDao.queryOrderAdmin(username);
    }

}

